﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using GameObjects;
using Utils;
using WebReferenceManager;

namespace GameManager
{
    public class GameManager
    {
        private ServerConnection serverConnection;

        public GameManager()
        {
            serverConnection = new ServerConnection();
            //const short communicationFrequency = 5000;

            //var mode = 

            //serverConnection.WebService.GetInitialGameState(56);

            while (!Console.KeyAvailable)
            {
                var games = serverConnection.WebService.GetGames();

                var lastServerConnection = DateTime.Now;

                var refreshGameList = false;

                var serverTime = serverConnection.WebService.GetServerTime();

                while (!refreshGameList)
                {
                    serverTime = serverTime.Add(DateTime.Now - serverTime);

                    Console.Clear();
                    Console.WriteLine("Games at " + serverConnection.WebService.Endpoint.Address);
                    Console.WriteLine("Server time: " + serverTime + ". Local time: " + DateTime.Now);
                    Console.WriteLine();

                    foreach (var game in games.OrderBy(o => o.TurnEnds))
                    {
                        Console.Write("Game \"" + game.Name + "\" (" + game.Id + ")");
                        Console.WriteLine(" turn " + game.Turn + " / " + game.TurnLimit + " ends in " + TimeSpanHelper.ConvertToString((game.TurnEnds - serverTime)) + ".");

                        if (GameState.GameTurnTimeExpired(serverTime, game.TurnEnds))
                        {
                            serverConnection.WebService.EndTurn(game.Id, game.Turn);
                            refreshGameList = true;
                        }
                        if (game.Turn >= game.TurnLimit)
                        {
                            serverConnection.WebService.EndGame(game.Id);
                            refreshGameList = true;
                        }
                    }
                    if (DateTime.Now - lastServerConnection > new TimeSpan(0, 0, 30))
                        refreshGameList = true;

                    Thread.Sleep(1000);
                }
            }
        }
    }
}
